<template>
  <view class="qz-form">
    <uni-forms ref="baseForm" :rules="newRules" :modelValue="baseFormData" labelWidth="80px">
      <uni-forms-item :label="field.label" :required="field.required" :name="field.name"
        v-for="(field, index) in newBody" :key="index">
        <uni-easyinput :required="field.required" :name="field.name" v-if="field.type === 'input'"
          v-model="baseFormData[field.name]" :placeholder="field.placeholder ? field.placeholder : ''" />
        <uni-easyinput :name="field.name" :required="field.required" type="textarea" v-if="field.type === 'textarea'"
          v-model="baseFormData[field.name]" :placeholder="field.placeholder ? field.placeholder : ''" />
        <uni-data-checkbox :name="field.name" :required="field.required" v-else-if="field.type === 'radio'"
          v-model="baseFormData[field.name]" :localdata="field.options" />
        <uni-data-checkbox :name="field.name" :required="field.required" v-else-if="field.type === 'checkbox'"
          v-model="baseFormData[field.name]" multiple :localdata="field.options" />
        <uni-datetime-picker :name="field.name" :required="field.required" type="datetime"
          v-else-if="field.type === 'datetime'" return-type="timestamp" v-model="baseFormData[field.name]" />
        <uni-data-picker :localdata="field.options" :name="field.name" :required="field.required"
          v-else-if="field.type === 'dataPicker'" v-model="baseFormData[field.name]" 
          :popup-title="`${field.label}`">
        </uni-data-picker>
      </uni-forms-item>
      <!-- <button type="primary" @click="submit('baseForm')">提交</button> -->
    </uni-forms>

  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
const props = defineProps({
  modelObj: {
    type: Object,
    required: true
  },
  formInfo: {
    type: Array,
    required: true,
    validator: (value) => value.every(item => item.label && item.name && item.type)
  }
})
const emit = defineEmits(['update:modelObj'])
// console.log("props", props)
// Refs
const baseForm = ref(null);
const current = ref(0);
const newRules = ref({});
const newBody = ref([]);

// Reactive data
const validate = (ref) => {
  // console.log('check',await baseForm.value.validate());
  return new Promise((resolve, reject) => {
    baseForm.value
      .validate()
      .then((res) => {
        resolve()
      })
      .catch((err) => {
        reject()
        console.log("err", err);
      });
  })
};

const baseFormData = computed({
  get() {
    return props.modelObj; // Getter
  },
  set(newValue) {
    emit('update:modelObj', newValue)
  }
});

// const newBody = computed( () => {
//   let bodyForm = props.formInfo;
//   let newBodyList = [];
//   bodyForm.forEach(async (item) => {
//     const { options } = item;
//     let newOptions = [];
//     if (options && typeof options === 'function') {
//       newOptions = await options()
//       console.log("newOptions",newOptions)
//     } else if (options) {
//       newOptions = options
//     }
//     newBodyList.push({
//         placeholder: item.placeholder || item.label || '',
//         ...item,
//         options:newOptions
//     })
//   })

// });
const setRules = () => {//设定规则
  const newBodyLeng = newBody.value;
  for (let i = 0; i < newBodyLeng.length; i++) {
    const { label, name, required, rules, type } = newBody.value[i];
    if (required) {
      let temp = {
        rules: []
      };
      switch (type) {
        case "select":
        case "radio":
        case "checkbox":
          temp.rules = [
            {
              required: true,
              errorMessage: `请选择${label}`,
            },
          ];
          break;
        default:
          temp.rules = [
            {
              required: true,
              errorMessage: `请输入${label}`,
            },
          ];
          break;
      }
      newRules.value[name] = rules || newRules.value[name] || temp;
    }
  }
  console.log("newRules", newRules)
  // baseForm.value.setRules(newRules.value)
}

// 重置
const reset = () => {
  baseForm.value.resetFields();
  baseForm.value.clearValidate();
};



// Lifecycle hooks
onMounted(() => {

});

watch(newBody, (newValue) => {
  setRules()
})
watch(
  () => props.formInfo,
  async (bodyForm) => {
    const results = await Promise.all(
      bodyForm.map(async (item) => {
        const { options } = item;
        let newOptions = [];
        if (options && typeof options === 'function') {
          newOptions = await options(); // 异步获取 options
        } else if (options) {
          newOptions = options;
        }
        return {
          placeholder: item.placeholder || item.label || '',
          ...item,
          options: newOptions,
        };
      })
    );
    newBody.value = results; // 更新 ref
  },
  { immediate: true } // 立即执行一次
);
defineExpose({
  validate,
  reset
})
</script>

<style lang="scss">
.example {
  padding: 15px;
  background-color: #fff;
}

.segmented-control {
  margin-bottom: 15px;
}

.button-group {
  margin-top: 15px;
  display: flex;
  justify-content: space-around;
}

.form-item {
  display: flex;
  align-items: center;
  flex: 1;
}

.button {
  display: flex;
  align-items: center;
  height: 35px;
  line-height: 35px;
  margin-left: 10px;
}

.qz-form {
  padding: 30rpx;
}
</style>